//
//  SINASelectLocationViewController.m
//  sinashebao
//
//  Created by  androidlongs on 2018/4/8.
//  Copyright © 2018年  androidlongs. All rights reserved.
//

#import "SINASelectLocationViewController.h"

#import <MAMapKit/MAMapKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import "SINALocationSelectTableViewCell.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import "SINACircularBeadUtils.h"
#import "SINAViewShadowUtils.h"
#import "SINASearchLocationViewController.h"
@interface SINASelectLocationViewController ()<AMapSearchDelegate,MAMapViewDelegate,UITableViewDelegate,UITableViewDataSource,AMapLocationManagerDelegate>
//地图
@property (weak, nonatomic) IBOutlet UIView *mapParentView;
//列表
@property (weak, nonatomic) IBOutlet UIView *locationListParentView;
@property (weak, nonatomic) IBOutlet UITableView *locationTableView;

@property(nonatomic,strong) AMapLocationManager *locationManager;
@property(nonatomic,strong) MAMapView *mapView;


@property(strong,nonatomic) NSMutableArray<SINALocationSelectModel *> *datalist;

@property(strong,nonatomic) NSMutableArray<MAPointAnnotation *> *annotationList;

@property(strong,nonatomic) AMapSearchAPI * search;

@property (weak, nonatomic) IBOutlet UILabel *noSearchLocationLabel;


@property (nonatomic, strong) MAPointAnnotation *poiAnnotation;


@property(nonatomic,strong) SINALocationSelectModel *currentSelectModel;

@property(nonatomic,strong)  UILabel *searchLabel ;

@property(nonatomic,strong) NSString *latitude;
@property(nonatomic,strong) NSString *longitude;

@property(nonatomic,assign) CGFloat  latitudes;
@property(nonatomic,assign) CGFloat  longitudes;

@property(nonatomic,strong) NSString *currentCity;

@end

@implementation SINASelectLocationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"选择地点";
    self.datalist =[[NSMutableArray alloc]init];
    self.annotationList =[[NSMutableArray alloc]init];
    
    
    [self initViewFunction];
    
}

//选择地点完成
-(void)selectLocationFinish{
    BOOL isSelect=NO;
    for (NSInteger i=0; i<self.datalist.count; i++) {
        SINALocationSelectModel *itemModel=self.datalist[i];
        if (itemModel.isSelect) {
            isSelect=YES;
        }
    }
    if (!isSelect) {
        [YPXToastView showToastViewWithText:@"请选择活动地点" andDuration:1 andParentView:self.view];
        return;
    }
    [self.navigationController popViewControllerAnimated:YES];
}

-(void) initViewFunction{
    
    
    self.locationTableView.delegate=self;
    self.locationTableView.dataSource=self;
    self.locationTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.locationTableView.backgroundColor=[UIColor colorWithHexString:@"#eeeeee"];
    self.locationTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
     [SINACircularBeadUtils makeCircularBead:4 andView: self.locationListParentView andIsSetBackground:NO];
    
    UIBarButtonItem *askListButton = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStyleDone target:self action:@selector(selectLocationFinish)];
    //[askListButton setImage:[UIImage imageNamed:@"ask_list"]];
    self.navigationItem.rightBarButtonItem = askListButton;
    
    
    UIView *titleBackGroundView = [[UIView alloc] initWithFrame:CGRectMake(12, 14, mainW-24, 41)];
    titleBackGroundView.backgroundColor=[UIColor colorWithRed:(255/255.0)  green:(255/255.0)  blue:(255/255.0)  alpha:0.1];
    [self.view addSubview:titleBackGroundView];
    [SINAViewShadowUtils updateViewShadow:titleBackGroundView andWithShadowWidth:2 andWithShadowHeight:4 andWithShadowColor:[UIColor colorWithHexString:@"#bbbbbb"]];
    
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, mainW-24, 41)];
//    UIColor *color =  [UIColor colorWithRed:(255/255.0)  green:(255/255.0)  blue:(255/255.0)  alpha:1.0];
    [titleView setBackgroundColor:[UIColor colorWithHexString:@"#FFFFFF"]];
    
    [titleBackGroundView  addSubview:titleView];
    //self.navigationItem.titleView = titleView;
    
    
    UIImageView *searchImageView = [[UIImageView alloc]init];
    searchImageView.frame=CGRectMake(0, 0, 40, 41);
    searchImageView.image=[UIImage imageNamed:@"location_normal_icon"];
    [titleView addSubview:searchImageView];
    
    [SINACircularBeadUtils makeCircularBead:6 andView:titleView];
    
    UIView *diviView = [[UIView alloc]init];
    diviView.frame=CGRectMake(CGRectGetMaxX(searchImageView.frame), 0, 1, CGRectGetHeight(titleView.frame));
    diviView.backgroundColor=[UIColor colorWithHexString:@"#eeeeee"];
    [titleView addSubview:diviView];
    
    
    //search_icon
   
    UIImageView *iv = [[UIImageView alloc] init];
    iv.backgroundColor = [UIColor clearColor];
    iv.image = [UIImage imageNamed:@"search_black_icon"];
    iv.frame = CGRectMake(CGRectGetMaxX(diviView.frame)+16, CGRectGetHeight(titleView.frame)/2-6, 12, 12);
    [titleView addSubview:iv];
    
    CGRect rect = CGRectMake(CGRectGetMaxX(iv.frame)+12, CGRectGetHeight(titleView.frame)/2-11, CGRectGetWidth(titleView.frame)-CGRectGetMaxX(iv.frame)-12, 22);
    UILabel *searchLabel = [[UILabel alloc] initWithFrame:rect];
    self.searchLabel=searchLabel;
    searchLabel.text = @"搜索";
    searchLabel.textColor=[UIColor colorWithHexString:@"#787878"];
    searchLabel.font=[UIFont systemFontOfSize:15];
     [titleView addSubview:searchLabel];
    
    [[SINAUiviewClickLiserner alloc]viewClickFunction:searchLabel andWithBlick:^(UIView *view) {
        DLog(@"搜索页面");
        SINASearchLocationViewController *searchLocationController =[[SINASearchLocationViewController alloc]init];
        [self.navigationController pushViewController:searchLocationController animated:YES];
    }];
    
    
    
    ///地图需要v4.5.0及以上版本才必须要打开此选项（v4.5.0以下版本，需要手动配置info.plist）
    [AMapServices sharedServices].enableHTTPS = YES;
    
    ///初始化地图
    MAMapView *_mapView = [[MAMapView alloc] initWithFrame:self.mapParentView.bounds];
    
    ///把地图添加至view
    [self.mapParentView addSubview:_mapView];
    
    ///如果您需要进入地图就显示定位小蓝点，则需要下面两行代码
    _mapView.showsUserLocation = YES;
    _mapView.userTrackingMode = MAUserTrackingModeFollow;
    _mapView.zoomLevel=16;
    _mapView.touchPOIEnabled=YES;
    _mapView.showsScale= NO;  //设置成NO表示不显示比例尺；YES表示显示比例尺
    //_mapView.scaleOrigin= CGPointMake(_mapView.scaleOrigin.x, 22);  //设置比例尺位置
    _mapView.showsCompass= NO; // 设置成NO表示关闭指南针；YES表示显示指南针
    _mapView.compassOrigin= CGPointMake(_mapView.compassOrigin.x, 22); //设置指南针位置
    _mapView.showsScale=YES;
    
    _mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    
    [_mapView setCompassImage:[UIImage imageNamed:@"compass"]];
    
    self.mapView = _mapView;
    self.mapView.delegate=self;
    
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;
    
    
    [self configLocationManager];
    //[self startSerialLocation];
    self.noSearchLocationLabel.backgroundColor=[UIColor whiteColor];
    [[SINAUiviewClickLiserner alloc]viewClickFunction:self.noSearchLocationLabel andWithBlick:^(UIView *view) {
        self.searchName = nil;
        self.searchLabel.text=@"搜索";
        [self updateSearchFunction];
    }];
    
    [[SINAUiviewClickLiserner alloc]viewClickFunction:searchImageView andWithBlick:^(UIView *view) {
        DLog(@"回到当前位置");
        searchImageView.image=[UIImage imageNamed:@"location_select_icon"];
         [self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(self.latitudes,self.longitudes) animated:YES];
        [YPXToastView showToastViewWithText:@"已回到当前位置" andDuration:3 andParentView:self.view];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1* NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            searchImageView.image=[UIImage imageNamed:@"location_normal_icon"];
        });
       
    }];
    
    UIView *zoomPannelView = [self makeZoomPannelView];
    
    
    
    CGRect preFrame =zoomPannelView.frame;
    preFrame.origin.y= CGRectGetMinY(self.locationListParentView.frame)-100;
    preFrame.origin.x=mainW-10-CGRectGetWidth(zoomPannelView.frame);
    
    zoomPannelView.frame = preFrame;
    
    zoomPannelView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin;
    
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchLocationNotificationAction:) name:notificationKeySearchLocation object:nil];
    
    
    
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(100*NSEC_PER_MSEC)), dispatch_get_main_queue(), ^{
        CGRect preSelectLocationFrame =self.locationListParentView.frame;
        preSelectLocationFrame.origin.y= preSelectLocationFrame.origin.y+mainH/2;
        self.locationListParentView.frame = preSelectLocationFrame;
    });
    
}
- (void)searchLocationNotificationAction:(NSNotification *)notification{
    
    NSString *searchKey = notification.userInfo[@"searchKey"];
    NSLog(@"搜索地点通知 %@",searchKey);
    self.searchName=searchKey;
    self.searchLabel.text=searchKey;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(600*NSEC_PER_MSEC)), dispatch_get_main_queue(), ^{
        [self updateSearchFunction];
    });
}
-(void) updateSearchFunction{
    [self startLoading];
//    AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
//
//    request.location            =[AMapGeoPoint locationWithLatitude:[self.latitude integerValue] longitude:[self.longitude integerValue]];
//    if (self.searchName!=nil) {
//        request.keywords= self.searchName;
//    }
//    /* 按照距离排序. */
//    request.sortrule            = 0;
//    request.requireExtension    = YES;
//    request.types=@"汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施";

    
    AMapPOIKeywordsSearchRequest *request = [[AMapPOIKeywordsSearchRequest alloc] init];
    
    request.keywords            = self.searchName;
    request.city                = self.currentCity;
    request.sortrule=0;
    request.offset=50;
    //request.types =@"操场|跑步|公园|健身|健身房";
//    request.types               = @"高等院校|汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施|运动场所|休息场所";
    request.requireExtension    = YES;
    
    /*  搜索SDK 3.2.0 中新增加的功能，只搜索本城市的POI。*/
   // request.cityLimit           = YES;
    request.requireSubPOIs      = YES;
    
    [self.search AMapPOIKeywordsSearch:request];
}

/* POI 搜索回调. */
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
    
    [self stopLoading];
    [self.datalist removeAllObjects];
    [self.locationTableView reloadData];
    [self.mapView removeAnnotations:self.annotationList];
    
   
    if (self.locationListParentView.hidden==YES) {
         CGRect preSelectLocationFrame =self.locationListParentView.frame;
        preSelectLocationFrame.origin.y= preSelectLocationFrame.origin.y-mainH/2;
        self.locationListParentView.hidden=NO;
        [UIView animateWithDuration:0.25 animations:^{
            self.locationListParentView.frame = preSelectLocationFrame;
        } completion:^(BOOL finished) {
            [self updateSearchPoiFunction:response];
        }];
    }else{
         [self updateSearchPoiFunction:response];
    }
    
   
    
    
   
}

-(void) updateSearchPoiFunction:(AMapPOISearchResponse *)response{
    if (response.pois.count == 0)
    {
        self.noSearchLocationLabel.hidden = NO;
        return;
    }else{
        self.noSearchLocationLabel.hidden = YES;
    }
    
    DLog(@"搜索回调");
    
    
    
    //解析response获取POI信息，具体解析见 Demo
    NSArray<AMapPOI *> *pois =response.pois;
    
    for (NSInteger i=0; i<pois.count; i++) {
        AMapPOI *poi = pois[i];
        DLog(@"poi name is %@",poi.name);
        
        SINALocationSelectModel *model =[[SINALocationSelectModel alloc]init];
        model.name = poi.name;
        if(model.name.length<=4){
            model.name=[NSString stringWithFormat:@"%@%@",poi.district,poi.name];
        }
        model.distance = [NSString stringWithFormat:@"%ld",(long)poi.distance];
        model.latitude=poi.location.latitude;
        model.longitude=poi.location.longitude;
        
        CLLocation *orig=[[CLLocation alloc] initWithLatitude:model.latitude  longitude:model.longitude];
        CLLocation* dist=[[CLLocation alloc] initWithLatitude:[self.latitude doubleValue]  longitude:[self.longitude doubleValue]];
        
        CLLocationDistance kilometers=[orig distanceFromLocation:dist];
        
        model.distance = [NSString stringWithFormat:@"%ld",(long)kilometers];
        model.distance2=kilometers;
        [self.datalist addObject:model];
        
        
        MAPointAnnotation *pointAnnotation = [[MAPointAnnotation alloc] init];
        pointAnnotation.coordinate = CLLocationCoordinate2DMake(poi.location.latitude, poi.location.longitude);
        pointAnnotation.title = poi.name;
        //pointAnnotation.subtitle = @"阜通东大街6号";
        [self.annotationList addObject:pointAnnotation];
        [self.mapView addAnnotation:pointAnnotation];
    }
    NSArray *array =[NSArray arrayWithArray:self.datalist];
    NSSortDescriptor * d1 = [NSSortDescriptor sortDescriptorWithKey:@"distance2" ascending:YES];
    NSArray * descripts = @[d1];
    
    NSArray *array2 = [array sortedArrayUsingDescriptors:descripts];
    self.datalist = [NSMutableArray arrayWithArray:array2];
    [self.locationTableView reloadData];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.datalist.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    SINALocationSelectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SINALocationSelectTableViewCell"];
    
    if (cell == nil) {
        cell= [[[NSBundle mainBundle]loadNibNamed:@"SINALocationSelectTableViewCell" owner:nil options:nil] firstObject];
        
    }
    
    cell.locationBlock = ^(SINALocationSelectModel *model) {
        for (NSInteger i=0; i<self.datalist.count; i++) {
            SINALocationSelectModel *itemModel=self.datalist[i];
            itemModel.isSelect = NO;
            if ([itemModel.name isEqualToString:model.name]) {
                itemModel.isSelect=YES;
                [self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(itemModel.latitude ,itemModel.longitude) animated:YES];
                for (NSInteger j=0; j<self.annotationList.count; j++) {
                    MAPointAnnotation * annotation = self.annotationList[j];
                    if ([annotation.title isEqualToString:itemModel.name]) {
                        [self.mapView selectAnnotation:annotation animated:YES];
                    }
                }
                
            }
        }
        
        [self.locationTableView reloadData];
    };
    
    SINALocationSelectModel *model= self.datalist[indexPath.row];
    cell.model=model;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell ;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 58;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    //    NSInteger index = indexPath.row;
}




- (void)configLocationManager
{
    self.locationManager = [[AMapLocationManager alloc] init];
    
    [self.locationManager setDelegate:self];
    
    [self.locationManager setPausesLocationUpdatesAutomatically:NO];
    
    [self.locationManager setAllowsBackgroundLocationUpdates:NO];
    
    // 带逆地理信息的一次定位（返回坐标和地址信息）
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    //   定位超时时间，最低2s，此处设置为2s
    self.locationManager.locationTimeout =2;
    //   逆地理请求超时时间，最低2s，此处设置为2s
    self.locationManager.reGeocodeTimeout = 2;
    
    self.locationManager.locatingWithReGeocode=NO;
    
    // 带逆地理（返回坐标和地址信息）。将下面代码中的 YES 改成 NO ，则不会返回地址信息。
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        
        if (error)
        {
            DLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
            
            if (error.code == AMapLocationErrorLocateFailed)
            {
                return;
            }
        }
        
        DLog(@"location:%@", location);
        
        if (regeocode)
        {
            DLog(@"reGeocode:%@", regeocode);
            
            self.latitude = [NSString stringWithFormat:@"%f",location.coordinate.latitude];
            self.latitudes=location.coordinate.latitude;
            self.longitude = [NSString stringWithFormat:@"%f",location.coordinate.longitude];
            self.currentCity = regeocode.city;
            self.longitudes=location.coordinate.longitude;
          
            
            [self updateSearchFunction];
            
            
            MAPointAnnotation *anntation = [[MAPointAnnotation alloc] init];
            
            anntation.coordinate = CLLocationCoordinate2DMake( location.coordinate.latitude ,location.coordinate.longitude);
            
            self.mapView.centerCoordinate = anntation.coordinate;
        }
    }];
}

- (void)startSerialLocation
{
    //开始定位
    [self.locationManager startUpdatingLocation];
}

- (void)stopSerialLocation
{
    //停止定位
    [self.locationManager stopUpdatingLocation];
}

- (void)amapLocationManager:(AMapLocationManager *)manager didFailWithError:(NSError *)error
{
    //定位错误
    DLog(@"%s, 定位错误 amapLocationManager = %@, error = %@", __func__, [manager class], error);
}

- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location
{
    //定位结果
    DLog(@" 定位结果 location:{lat:%f; lon:%f; accuracy:%f}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy);
    
    
    
}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
        MAPinAnnotationView*annotationView = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        if (annotationView == nil)
        {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
        }
        
        annotationView.canShowCallout= YES;       //设置气泡可以弹出，默认为NO
        annotationView.animatesDrop = NO;        //设置标注动画显示，默认为NO
        annotationView.draggable = YES;        //设置标注可以拖动，默认为NO
        annotationView.pinColor = MAPinAnnotationColorPurple;
        
        //设置
        if ([annotation.title isEqualToString:@"当前位置"]) {
            return nil;
        } else {
            return annotationView;
        }
        
        
    }
    return nil;
}




- (void)zoomPlusAction
{
    CGFloat oldZoom = self.mapView.zoomLevel;
    [self.mapView setZoomLevel:(oldZoom + 1) animated:YES];
    self.mapView.showsScale = YES;
}

- (void)zoomMinusAction
{
    CGFloat oldZoom = self.mapView.zoomLevel;
    [self.mapView setZoomLevel:(oldZoom - 1) animated:YES];
    self.mapView.showsScale = NO;
}


- (UIView *)makeZoomPannelView
{
    //33  x 3
    UIView *ret = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 33, 68)];
    ret.backgroundColor=[UIColor colorWithHexString:@"#ffffff"];
    [SINACircularBeadUtils makeCircularBead:3 andView:ret];
    [self.mapParentView addSubview:ret];
    
   
    
    
    
    UIButton *incBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, 10, CGRectGetWidth(ret.frame)-20, CGRectGetWidth(ret.frame)-20)];
    [incBtn setImage:[UIImage imageNamed:@"increase"] forState:UIControlStateNormal];
    //[incBtn sizeToFit];
    [incBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [incBtn addTarget:self action:@selector(zoomPlusAction) forControlEvents:UIControlEventTouchUpInside];
    [ret addSubview:incBtn];
    
    UIView *diviView2 =[[UIView alloc] initWithFrame:CGRectMake(8,34, CGRectGetWidth(ret.frame)-8-8, 1)];
    diviView2.backgroundColor=[UIColor colorWithHexString:@"#eeeeee"];
    [ret addSubview:diviView2];
    
    UIButton *decBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, 34+8, CGRectGetWidth(ret.frame)-20, CGRectGetWidth(ret.frame)-20)];
    [decBtn setImage:[UIImage imageNamed:@"decrease"] forState:UIControlStateNormal];
    //[decBtn sizeToFit];
    [decBtn addTarget:self action:@selector(zoomMinusAction) forControlEvents:UIControlEventTouchUpInside];
    [decBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    
    [ret addSubview:decBtn];
    
    return ret;
}


- (MAPointAnnotation *)annotationForTouchPoi:(MATouchPoi *)touchPoi
{
    if (touchPoi == nil)
    {
        return nil;
    }
    
    MAPointAnnotation *annotation = [[MAPointAnnotation alloc] init];
    
    annotation.coordinate = touchPoi.coordinate;
    annotation.title      = touchPoi.name;
    
    return annotation;
}
- (void)mapView:(MAMapView *)mapView didTouchPois:(NSArray *)pois
{
    if (pois.count == 0)
    {
        return;
    }
    
    MAPointAnnotation *annotation = [self annotationForTouchPoi:pois[0]];
    
    /* Remove prior annotation. */
    [self.mapView removeAnnotation:self.poiAnnotation];
    
    [self.mapView addAnnotation:annotation];
    [self.mapView selectAnnotation:annotation animated:YES];
    
    self.poiAnnotation = annotation;
}

-(void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view{
    
    MAPointAnnotation *anntation  = view.annotation;\
    [self stopLoading];
    
    DLog(@"选中 poi %@ %f  %f ",anntation.title,anntation.coordinate.latitude,anntation.coordinate.longitude);
    
    SINALocationSelectModel *model = [[SINALocationSelectModel alloc]init];
    model.name=anntation.title;
    
    CLLocation *orig=[[CLLocation alloc] initWithLatitude:[self.latitude doubleValue] longitude:[self.longitude doubleValue]];
    
    CLLocation* dist=[[CLLocation alloc] initWithLatitude:anntation.coordinate.latitude longitude:anntation.coordinate.longitude];
    
    CLLocationDistance kilometers=[orig distanceFromLocation:dist];
    
    NSString *kilometersStr = [NSString stringWithFormat:@"%f",kilometers];
    model.distance=[NSString stringWithFormat:@"%d",[kilometersStr intValue]];
    model.isSelect=YES;
    model.latitude =anntation.coordinate.latitude;
    model.longitude =anntation.coordinate.longitude;
    
    BOOL isNew=YES;
    NSInteger preIndex=0;
    SINALocationSelectModel *preModel;
    for (NSInteger i=0; i<self.datalist.count; i++) {
        SINALocationSelectModel *itemModel=self.datalist[i];
        itemModel.isSelect = NO;
        if ([itemModel.name isEqualToString:model.name]) {
            isNew=NO;
            preModel = itemModel;
            preIndex = i;
            itemModel.isSelect=YES;
        }
    }
    if (isNew) {
        [self.datalist insertObject:model atIndex:0];
        [self.locationTableView reloadData];
        NSIndexPath * dayOne = [NSIndexPath indexPathForRow:preIndex inSection:0];
        [self.locationTableView scrollToRowAtIndexPath:dayOne atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }else{
        //        [self.datalist removeObject:preModel];
        //        [self.datalist insertObject:model atIndex:0];
        //        [self.locationTableView reloadData];
        [self.locationTableView reloadData];
        NSIndexPath * dayOne = [NSIndexPath indexPathForRow:preIndex inSection:0];
        [self.locationTableView scrollToRowAtIndexPath:dayOne atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
    
}


-(void)viewDidDisappear:(BOOL)animated{
    for (NSInteger i=0; i<self.datalist.count; i++) {
        SINALocationSelectModel *itemModel=self.datalist[i];
        
        if (itemModel.isSelect) {
            //添加 字典，将label的值通过key值设置传递
            NSDictionary *dict =[[NSDictionary alloc]initWithObjectsAndKeys:itemModel.name,@"locationName",nil];
            //创建通知
            NSNotification *notification =[NSNotification notificationWithName:@"updateLocation" object:nil userInfo:dict];
            
            //通过通知中心发送通知
            
            [[NSNotificationCenter defaultCenter] postNotification:notification];
            
        }
    }
    
}
@end
